//
//  YLUserAccountViewModel.swift
//  weiBo
//
//  Created by 杨雷 on 2016/12/4.
//  Copyright © 2016年 Yang.L. All rights reserved.
//

import UIKit

class YLUserAccountViewModel: NSObject {
    
    static let sharedUserAccount : YLUserAccountViewModel = YLUserAccountViewModel()
    
    var userAccount : YLUserAccount?{
        return YLUserAccount.loadUserAccount()
    }
    
    //判断是否登录
    var isLogin : Bool {
        return accessToken != nil
    }
    
    
    var accessToken : String? {
        guard let token = userAccount?.access_token else {
            return nil
        }
        
        if userAccount?.expiresDate?.compare(Date()) == ComparisonResult.orderedDescending {
            //不过期
            return token
        } else {
            //过期
            return nil
        }
        
        
        
    }
    
    //通过code 获取accessToken
    func requestAccessToken(code: String, callBack: @escaping (Bool) -> ()) {
        
        YLNetworkTools.sharedTools.requestAccesstoken(code: code, callBack: {(response, error) -> () in
            if error != nil {
                print(error!)
                callBack(false)
                return
            }
            
            //请求成功
            let dic = response as! [String: Any]
            //转模型
            let userAccount = YLUserAccount(dic: dic)
            
            self.requestUserInfo(userAccount: userAccount, callBack: callBack)
            
        })
        
    }
    //根据id和accesstoken获取用户信息
    func requestUserInfo (userAccount :YLUserAccount, callBack: @escaping (Bool) -> ()) {
        let accessToken = userAccount.access_token!
        let uid = userAccount.uid
        YLNetworkTools.sharedTools.requestUserInfo(accessToken: accessToken, uid: uid, callBack: {(response, error) -> () in
            if error != nil{
                print(error!)
                callBack(false)
                return
            }
            
            //请求成功
            let dic = response as! [String: Any]
            
            let name = dic["name"]
            
            let avatar_large = dic["avatar_large"]
            
            userAccount.name = name as! String?
            userAccount.avatar_large = avatar_large as? String
            userAccount.saveUserAccount()
            
            callBack(true)
        })
    }

    
    
    
    
    
}
